/*
 * @lc app=leetcode.cn id=457 lang=typescript
 *
 * [457] 环形数组是否存在循环
 */

// @lc code=start
function circularArrayLoop(nums: number[]): boolean {
  const m = nums.length;
  const next = (idx: number): number => {
    // 避免负数的情况，保证范围在[0,m)
    return (((idx + nums[idx]) % m) + m) % m;
  };

  for (let i = 0; i < m; i++) {
    let slow = i;
    let fast = next(slow);
    // 需要环的元素全正或者全负
    while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(fast)] > 0) {
      if (slow === fast) {
        // 如果下一步还是移动回来，表示这个循环区间长度<=1，不满足k>1条件
        if (slow === next(slow)) break;
        return true;
      }
      slow = next(slow);
      fast = next(next(fast));
    }
  }

  return false;
}
// @lc code=end
